package cn.xlmdz.subsoilerinfoquery.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xlmdz.subsoilerinfoquery.R;
import cn.xlmdz.subsoilerinfoquery.bean.LoginBean;
import cn.xlmdz.subsoilerinfoquery.bean.OrganizeBean;
import cn.xlmdz.subsoilerinfoquery.bean.tree.Cooperative;
import cn.xlmdz.subsoilerinfoquery.bean.tree.CooperativeNodeBinder;
import cn.xlmdz.subsoilerinfoquery.bean.tree.Organize;
import cn.xlmdz.subsoilerinfoquery.bean.tree.OrganizeNodeBinder;
import cn.xlmdz.subsoilerinfoquery.databinding.ActivityQueryOrganizeBinding;
import cn.xlmdz.subsoilerinfoquery.http.ApiEngine;
import cn.xlmdz.subsoilerinfoquery.http.ApiServices;
import cn.xlmdz.subsoilerinfoquery.utils.SharedPrefsUtil;
import cn.xlmdz.subsoilerinfoquery.utils.ToastUtil;
import cn.xlmdz.subsoilerinfoquery.view.LoadingDialog;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import tellh.com.recyclertreeview_lib.TreeNode;
import tellh.com.recyclertreeview_lib.TreeViewAdapter;

public class QueryOrganizeActivity extends AppCompatActivity {

    private ActivityQueryOrganizeBinding viewBinding;
    private LoadingDialog loadingDialog;

    private TreeViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityQueryOrganizeBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());

        initViews();
        getOrganizeTreeData();
    }

    private void initViews() {
        viewBinding.tvTitle.setText("组织列表");
        viewBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getOrganizeTreeData() {
        showLoading();
        String token = SharedPrefsUtil.getStringPreference(this, "loginToken");
        if (!TextUtils.isEmpty(token)) {
            ApiServices services = ApiEngine.getInstance().getApiService();
            Observable<OrganizeBean> observable = services.getOrganizeTreeData(token);
            observable.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<OrganizeBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull OrganizeBean organizeBean) {
                            createTree(organizeBean);
                            hideLoading();
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            ToastUtil.showTextToast("初始化组织列表失败");
                            hideLoading();
                        }

                        @Override
                        public void onComplete() {
                            hideLoading();
                        }
                    });
        }
    }

    private void createTree(OrganizeBean dataBean) {
        List<TreeNode> nodes = new ArrayList<>();
        for (int i = 0; i < dataBean.getData().size(); i++) {
            OrganizeBean.DataBean data = dataBean.getData().get(i);

            if (data.getId() < 600000) {
                TreeNode<Organize> node = new TreeNode<>(new Organize(data.getId(), data.getTitle(), data.getParentId()));
                nodes.add(node);

                if (data.getChildren() != null) {
                    createOrganizeNode(data.getChildren(), node);
                }
            } else {
                TreeNode<Cooperative> node = new TreeNode<>(new Cooperative(data.getId(), data.getTitle(), data.getParentId()));
                nodes.add(node);
            }
        }

        viewBinding.recycleTreeOrganize.setLayoutManager(new LinearLayoutManager(QueryOrganizeActivity.this));
        adapter = new TreeViewAdapter(nodes, Arrays.asList(new CooperativeNodeBinder(), new OrganizeNodeBinder()));
        adapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
            @Override
            public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
                if (!node.isLeaf()) {
                    //Update and toggle the node.
                    onToggle(!node.isExpand(), holder);
//                        if (!node.isExpand())
//                            adapter.collapseBrotherNode(node);
                } else {
                    try {
                        Cooperative nodeData = (Cooperative) node.getContent();
                        Intent intent = new Intent(QueryOrganizeActivity.this, CarListActivity.class);
                        intent.putExtra("orgId", nodeData.id + "");
                        intent.putExtra("orgName", nodeData.title);
                        intent.putExtra("parentId", nodeData.parentId + "");
                        startActivity(intent);
                    } catch (Exception e) {

                    }
                }
                return false;
            }

            @Override
            public void onToggle(boolean isExpand, RecyclerView.ViewHolder holder) {
                OrganizeNodeBinder.ViewHolder dirViewHolder = (OrganizeNodeBinder.ViewHolder) holder;
                final ImageView ivArrow = dirViewHolder.getIvArrow();
                int rotateDegree = isExpand ? 90 : -90;
                ivArrow.animate().rotationBy(rotateDegree)
                        .start();
            }
        });
        viewBinding.recycleTreeOrganize.setAdapter(adapter);
    }

    private void createOrganizeNode(List<OrganizeBean.Children> beanList, TreeNode parentNode) {
        for (int i = 0; i < beanList.size(); i++) {
            TreeNode node = addNode(beanList.get(i), parentNode);
            if (beanList.get(i).getChildren() != null) {
                createOrganizeNode(beanList.get(i).getChildren(), node);
            }
        }
    }

    private TreeNode addNode(OrganizeBean.Children bean, TreeNode parentNode) {
        if (bean.getId() < 600000) {
            TreeNode<Organize> childNode = null;
            if (bean != null) {
                childNode = new TreeNode<>(new Organize(bean.getId(), bean.getTitle(), bean.getParentId()));
            }
            parentNode.addChild(childNode);
            return childNode;
        } else {
            TreeNode<Cooperative> childNode = null;
            if (bean != null) {
                childNode = new TreeNode<>(new Cooperative(bean.getId(), bean.getTitle(), bean.getParentId()));
            }
            parentNode.addChild(childNode);
            return childNode;
        }
    }

    public void showLoading() {
        if (loadingDialog == null)
            loadingDialog = new LoadingDialog(this, "加载中…");
        if (!loadingDialog.isShowingNew())
            loadingDialog.show();
    }

    public void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowingNew())
            loadingDialog.close();
    }
}